package com.googlecode.jch.plugin;

import com.intellij.openapi.actionSystem.*;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.project.Project;
import com.intellij.psi.*;

/**
 * @author Iskander Akishev
 */
public abstract class AbstractActionOverSolution extends AnAction {

	protected PsiClass solutionClass;

	@Override
	public void update(AnActionEvent e) {
		Presentation presentation = e.getPresentation();
		solutionClass = getSolutionClass(e.getDataContext());
		presentation.setEnabled(solutionClass != null);
		presentation.setVisible(solutionClass != null || e.getPlace().equals(ActionPlaces.MAIN_TOOLBAR));
	}

	private PsiClass getSolutionClass(DataContext dataContext) {
		Project project = PlatformDataKeys.PROJECT.getData(dataContext);
		if (project == null) return null;

		Editor editor = PlatformDataKeys.EDITOR.getData(dataContext);
		if (editor != null) {
			PsiFile file = PsiDocumentManager.getInstance(project).getPsiFile(editor.getDocument());
			return file == null ? null : getSolutionClassFromFile(file);
		}

		PsiElement element = DataKeys.PSI_ELEMENT.getData(dataContext);

		if (element instanceof PsiFile) {
			return getSolutionClassFromFile((PsiFile)element);
		}

		while (element instanceof PsiMember) {
			if (element instanceof PsiClass) {
				PsiClass clazz = (PsiClass)element;
				if (JCHUtil.isSolutionClass(clazz)) return clazz;
			}
			element = ((PsiMember)element).getContainingClass();
		}
		return null;
	}

	private PsiClass getSolutionClassFromFile(PsiFile file) {
		if (!(file instanceof PsiClassOwner)) return null;
		PsiClass[] classes = ((PsiClassOwner)file).getClasses();
		for (PsiClass c : classes) {
			if (JCHUtil.isSolutionClass(c)) {
				return c;
			}
		}
		return null;
	}
}
